﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using PepsiCo.Business;

namespace PepsiCo.UI
{
    public partial class KPIExportReport : BasePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindDataReport();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        Dictionary<string, string> Kpi_Header
        {
            get{ return (Dictionary<string, string>)ViewState["Kpi_Header"];}
            set { ViewState["Kpi_Header"] = value; }
        }
        Dictionary<int, bool> columnVisble
        {
            get { return (Dictionary<int, bool>)ViewState["columnVisble"]; }
            set { ViewState["columnVisble"] = value; }
        }
        int indexOfCellPhoneNumber
        {
            get
            {
                if (ViewState["indexCellPhoneNumber"] == null) return 0;
                return (int)ViewState["indexCellPhoneNumber"];
            }
            set { ViewState["indexCellPhoneNumber"] = value; }
        }
        int indexOfCellReportTime
        {
            get
            {
                if (ViewState["indexOfCellReportTime"] == null) return 0;
                return (int)ViewState["indexOfCellReportTime"];
            }
            set { ViewState["indexOfCellReportTime"] = value; }
        }
        int indexOfCellMoGuid
        {
            get
            {
                if (ViewState["indexOfCellMoGuid"] == null) return 0;
                return (int)ViewState["indexOfCellMoGuid"];
            }
            set { ViewState["indexOfCellMoGuid"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                Kpi_Header = new Dictionary<string, string>();
                columnVisble = new Dictionary<int, bool>();
                foreach (var item in DB.PepsiKPIs)
                {
                    Kpi_Header.Add("idx" + item.kpi_id, item.kpi_name);
                }
                Kpi_Header.Add("Date_Reported", "Date Reported");
                Kpi_Header.Add("Staff_Name", "Staff Name");
                Kpi_Header.Add("StaffCode", "Staff Code");
                Kpi_Header.Add("Unit_Name", "Unit Name");
                Kpi_Header.Add("Phone_Number", "Phone Number");
                Kpi_Header.Add("Report_Time", "Report Time");
                PageSize = Convert.ToInt32(drdSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownUnit(CurUser.UnitID);
                BindDataReport();
            }
        }

        private void BindDropDownUnit(Guid? unitID)
        {
            foreach (var item in DB.pepsi_Units.Where(p => p.ID == unitID))
            {
                ddlUnit.Items.Add(new ListItem(item.Name, item.ID.ToString()));
                BindDropDownUnit(item.ID, "--");
            }
        }

        private void BindDropDownUnit(Guid? unitID, string ident)
        {
            var dataSource = DB.pepsi_Units.Where(p => p.ParentID == unitID).OrderBy(p => p.OrderID);
            foreach (var item in dataSource)
            {
                ddlUnit.Items.Add(new ListItem(ident + item.Name, item.ID.ToString()));
                BindDropDownUnit(item.ID, Server.HtmlDecode("&nbsp;&nbsp;&nbsp;") + ident);
            }
        }

        private void BindDataReport()
        {
            try
            {
                string phoneNumber = null;
                DateTime? reportDateFrom = null;
                DateTime? reportDateTo = null;
                DateTime? reportTimeFrom = null;
                DateTime? reportTimeTo = null;
                Guid? unitID = null;
                Guid? staffID = null;
                int? currentPage = pagingtop.CurrentPage;
                int? pageSize = pagingtop.PageSize;
                int? totalRecord = 0;
                if (!string.IsNullOrEmpty(txtPhoneNumber.Text.Trim())) phoneNumber = txtPhoneNumber.Text.Trim().ToNormalPhoneNumber();
                if (!string.IsNullOrEmpty(txtdate_reportedFrom.Text.Trim())) reportDateFrom = Convert.ToDateTime(txtdate_reportedFrom.Text.Trim());
                if (!string.IsNullOrEmpty(txtdate_reportedTo.Text.Trim())) reportDateTo = Convert.ToDateTime(txtdate_reportedTo.Text.Trim()).AddDays(1).AddSeconds(-1);
                if (!string.IsNullOrEmpty(ddlUnit.SelectedValue)) unitID = new Guid(ddlUnit.SelectedValue);
                grvStatistic.DataSource = DB.sp_pepsi_KPIExportReport(reportDateFrom, reportDateTo, staffID, unitID, phoneNumber, 
                                                                        reportTimeFrom, reportTimeTo,
                                                                        currentPage, pageSize, ref totalRecord);

                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRecord.Value;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvStatistic.DataBind();
                ltrInfo.Text = "Total pages: " + pagingtop.TotalPage; 
            }
            catch { }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindDataReport();
        }

        protected void drdSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(drdSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindDataReport();
            }
            catch { }
        }

        protected void grvStatistic_RowCreated(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType != DataControlRowType.Header)
                {
                    e.Row.Attributes.Add("onmouseover", "$(this).addClass('hover')");
                    e.Row.Attributes.Add("onmouseout", "$(this).removeClass('hover')");
                    if (e.Row.RowIndex % 2 != 0)
                        e.Row.Attributes.Add("class", "odd");
                }
            }
            catch { }
        }

        protected void grvStatistic_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (Kpi_Header == null)
                    Kpi_Header = (Dictionary<string, string>)ViewState["Kpi_Header"];
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    for (int i = 0; i < e.Row.Cells.Count; i++)
                    {
                        if (e.Row.Cells[i].Text == "Phone_Number") indexOfCellPhoneNumber = i;
                        if (e.Row.Cells[i].Text == "mo_guid") indexOfCellMoGuid = i;
                        if (e.Row.Cells[i].Text == "Report_Time") indexOfCellReportTime = i;
                        if (Kpi_Header.ContainsKey(e.Row.Cells[i].Text.Trim()))
                        {
                            e.Row.Cells[i].Text = Kpi_Header[e.Row.Cells[i].Text.Trim()];
                            if(!columnVisble.ContainsKey(i))
                                columnVisble.Add(i, true);
                        }
                        else
                        {
                            e.Row.Cells[i].Visible = false;
                            if (!columnVisble.ContainsKey(i))
                                columnVisble.Add(i, false);
                        }
                    }
                }

                else if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    var DataItem = (sp_pepsi_KPIExportReportResult)e.Row.DataItem;
                    if (!string.IsNullOrEmpty(e.Row.Cells[indexOfCellReportTime].Text))
                        e.Row.Cells[indexOfCellReportTime].Text = DataItem.Report_Time.Value.ToString("MM/dd/yyyy HH:mm:ss");
                    e.Row.Cells[indexOfCellPhoneNumber].Text =
                        "<a class='subs' href='#' onclick='javascript:GetMT(this); showdialog(); return false;'>" +
                            DataItem.Phone_Number +
                            "      <input type='hidden' value='" + DataItem.mo_guid + "' />" +
                        "</a>";
                    for (int i = 0; i < e.Row.Cells.Count; i++)
                    {
                        if (columnVisble.ContainsKey(i) && columnVisble[i])
                            e.Row.Cells[i].Visible = columnVisble[i];
                        else
                            e.Row.Cells[i].Visible = false;

                    }
                }
            }
            catch { }
        }

        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            string phoneNumber = null;
            DateTime? reportDateFrom = null;
            DateTime? reportDateTo = null;
            DateTime? reportTimeFrom = null;
            DateTime? reportTimeTo = null;
            Guid? unitID = null;
            Guid? staffID = null;
            int? currentPage = pagingtop.CurrentPage;
            int? pageSize = pagingtop.PageSize;
            int? totalRecord = 0;
            if (!string.IsNullOrEmpty(txtPhoneNumber.Text.Trim())) phoneNumber = txtPhoneNumber.Text.Trim().ToNormalPhoneNumber();
            if (!string.IsNullOrEmpty(txtdate_reportedFrom.Text.Trim())) reportDateFrom = Convert.ToDateTime(txtdate_reportedFrom.Text.Trim());
            if (!string.IsNullOrEmpty(txtdate_reportedTo.Text.Trim())) reportDateTo = Convert.ToDateTime(txtdate_reportedTo.Text.Trim()).AddDays(1).AddSeconds(-1);
            if (!string.IsNullOrEmpty(ddlUnit.SelectedValue)) unitID = new Guid(ddlUnit.SelectedValue);
            
            /*-------------------------------*/
            Response.Clear();
            Response.Buffer = true;
            //excel
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=KPIReport.xls");
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            var datasource  = DB.sp_pepsi_KPIExportReport(reportDateFrom, reportDateTo, staffID, unitID, phoneNumber,
                                                                    reportTimeFrom, reportTimeTo,
                                                                    1, 1000, ref totalRecord);
            string re = Utils.MSWordHeader() + Utils.MSWordTableContent<dynamic>(datasource) + Utils.MSWordFooter();
            Response.Write(re);                                                                                                          
            Response.Flush();                                                                                                            
            Response.End();
        }
    }
}